<template>
  <a-row>
    <!-- Left Navigation -->
    <Nav />

    <!-- Main Content -->
    <a-col :span="20" class="main-container">
      <div class="main-content bordered-section">
        <h3 class="section-title-h3">题目批改</h3>
        <a-row :gutter="16">
          <!-- Left Column -->
          <a-col class="gutter-row bordered-section" :span="10">
            <h4 class="section-subtitle">上传的题目</h4>
            <div class="uploaded-image">
              <img
                v-if="imageUrl"
                :src="imageUrl"
                alt="上传题目解答照片"
                style="max-width: 100%"
              />
            </div>
          </a-col>

          <!-- Upload Section -->
          <a-col class="gutter-row bordered-section" :span="4">
            <h4 class="section-subtitle">上传图片</h4>
            <div>
              <a-upload
                :list-type="'picture-card'"
                :show-upload-list="false"
                :before-upload="handleBeforeUpload"
              >
                <div>
                  <PlusOutlined />
                  <div style="margin-top: 8px"></div>
                </div>
              </a-upload>
            </div>
          </a-col>

          <!-- Server Response Section -->
          <!--          <a-col class="gutter-row bordered-section" :span="10">-->
          <!--            <h4 class="section-subtitle">答疑区</h4>-->

          <!-- Loading Animation -->
          <!--            <div v-if="isLoading" class="loading-container">-->
          <!--              <a-spin tip="正在加载中..." />-->
          <!--            </div>-->

          <!--            &lt;!&ndash; Server Response &ndash;&gt;-->
          <!--            <div v-else-if="responseMessage" class="response-message" >-->
          <!--              <p>Server Response:</p>-->
          <!--              <div v-html="formattedResponse"></div>-->
          <!--              <div class="formattedResponse" v-html="'$$'+formattedResponse+'$$'"/>-->
          <!--            </div>-->

          <!--          </a-col>-->
          <a-col class="gutter-row bordered-section" :span="10">
            <h4 class="section-subtitle">答疑区</h4>
            <div class="uploaded-image">
              <!--              <img-->
              <!--                  v-if="imageUrl"-->
              <!--                  src="C:Users\void\Pictures\sss.png"-->
              <!--                  alt="上传题目解答照片"-->
              <!--                  style="max-width: 100%;"-->
              <!--              />-->
              <img
                src="../assets/img.png"
                alt="da1dsa"
                style="max-width: 100%"
              />
            </div>
          </a-col>
        </a-row>
      </div>
    </a-col>
  </a-row>
</template>

<script>
import { ref, watch, onMounted } from "vue";
import { message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import axios from "axios";
import MathJax from "../common/MathJax";
import Nav from "@/components/Nav.vue";
export default {
  components: {
    Nav,
    PlusOutlined,
  },
  data() {
    return {
      latex: "",
      latexHtml: "",
    };
  },
  watch: {
    // 监视latex的变化
    latex() {
      this.$nextTick(function () {
        // Vue的DOM渲染是异步的
        if (MathJax.isMathjaxConfig) {
          // 是否配置MathJax
          MathJax.initMathjaxConfig();
        }
        MathJax.MathQueue("latexDiv"); // 渲染对应的id/class
      });
    },
  },
  setup() {
    const imageUrl = ref(null); // Local preview URL
    const responseMessage = ref(null); // Backend response message
    const formattedResponse = ref(null); // Formatted response with LaTeX rendered
    const isLoading = ref(false); // Loading animation state

    const formatResponse = (message) => {
      let formatted = message.replace(/\\n/g, "<br>").replace(/\\\\/g, "\\");
      formatted = formatted.replace(/\$(.*?)\$/g, (_, expr) => `\\(${expr}\\)`);
      return formatted;
    };

    watch(responseMessage, (newVal) => {
      formattedResponse.value = formatResponse(newVal);
      if (window.MathJax) {
        window.MathJax.typesetPromise();
      }
    });

    onMounted(() => {
      if (!window.MathJax) {
        const script = document.createElement("script");
        script.src =
          "https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.0/es5/tex-mml-chtml.js";
        script.async = true;
        script.onload = () => {
          if (window.MathJax) {
            window.MathJax.typesetPromise();
          }
        };
        document.head.appendChild(script);
      }
    });

    const handleBeforeUpload = async (file) => {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        message.error("You can only upload image files!");
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error("Image must be smaller than 2MB!");
        return false;
      }

      const reader = new FileReader();
      reader.onload = async (e) => {
        imageUrl.value = e.target.result;
        isLoading.value = true; // Show loading animation

        try {
          const response = await axios.post("http://127.0.0.1:5000/api/data", {
            image_base64: e.target.result,
          });
          responseMessage.value = response.data.message.content;
        } catch (error) {
          message.error("Failed to upload and process the image.");
          console.error(error);
        } finally {
          isLoading.value = false; // Hide loading animation
        }
      };
      reader.readAsDataURL(file);

      return false;
    };

    // const navigateTo = (destination) => {
    //   console.log(`Navigating to ${destination}`);
    //   // Add navigation logic here
    //   this.$router.push({ name: destination });
    // };

    return {
      imageUrl,
      responseMessage,
      formattedResponse,
      isLoading,
      handleBeforeUpload,
      // navigateTo,
    };
  },
  methods: {
    navigateTo(destination) {
      this.$router.push({ name: destination });
    },
  },
};
</script>

<style scoped>
/* General Styles */
.bordered-section {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-bottom: 16px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 2em;
  font-weight: bold;
  margin-bottom: 30px;
  color: white;
  padding-bottom: 29px;
  font-family: "Microsoft YaHei UI";
  font-weight: bold;
}

.section-subtitle {
  font-size: 1.2em;
  font-weight: bold;
  margin-bottom: 12px;
  color: #666;
  border-bottom: 1px solid #d9d9d9;
  padding-bottom: 6px;
}

/* Loading Animation */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  text-align: center;
}

/* Navigation Bar */
.nav-bar {
  height: 100vh;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  color: #fff;
}

.menu-container {
  text-align: center;
  background-image: url("../assets/bg.png"); /* 确保路径正确 */
  background-size: cover; /* 调整图片大小以覆盖整个背景 */
  background-position: center; /* 居中显示背景图片 */
  background-repeat: no-repeat; /* 防止背景重复 */
}

.menu-list {
  list-style: none;
  padding: 0;
  margin: 0;
  font-size: 30px;
  font-family: "Microsoft YaHei UI";
  font-weight: bold;
}

.menu-item {
  padding: 10px 0;
  cursor: pointer;
  color: #fff;
  transition: background-color 0.3s;
  margin: 5px 0;
}

.menu-item:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

/* Main Content */
.main-container {
  background-color: #f7f7f3;
  padding: 20px;
}

.uploaded-image img {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 8px;
}

.response-message {
  white-space: pre-wrap;
  word-break: break-word;
}

.response-message p {
  font-size: 16px;
  color: #333;
  line-height: 1.6;
}

.section-title-h3 {
  font-size: 1.5em;
  font-weight: bold;
  margin-bottom: 16px;
  color: black;
  padding-bottom: 8px;
}

.colortxt {
  font-size: 45px;
  background: linear-gradient(to right, white, pink);
  /* -webkit-background-clip: text; */
  color: transparent;
}
</style>
